<!--
 * @Descripttion: 产品表单
 * @LastEditors: xzh
 * @LastEditTime: 2023-11-01 19:59:42
-->
<template>
  <DileDrawer
    v-model="productForm.visible"
    :loading="productForm.loading"
    size="60%"
    @sure="hanldeSure"
  >
    <template #header>
      <span>{{
        $t(`table.btnArr.${!productForm.formData.id ? "add" : "edit"}`)
      }}</span>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        class="el-form-card"
        :model="productForm.formData"
        :rules="formRules"
        label-width="7rem"
        size="large"
        status-icon
      >
        <el-card>
          <template #header>
            <span>{{ $t("page.systemManageArr.productArr.productInfo") }}</span>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.systemManageArr.productArr.code')"
              prop="code"
            >
              <el-input
                v-model="productForm.formData.code"
                :placeholder="
                  $t('common.enter') +
                  $t('page.systemManageArr.productArr.code')
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.productArr.name')">
              <el-input
                v-model="productForm.formData.name"
                :placeholder="
                  $t('common.enter') +
                  $t('page.systemManageArr.productArr.name')
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('page.systemManageArr.productArr.classify')"
            >
              <el-select
                v-model="productForm.formData.categoryId"
                :placeholder="
                  $t('common.select') +
                  $t('page.systemManageArr.productArr.classify')
                "
              >
                <el-option
                  v-for="item in productForm.resoure.productClassifyArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.productArr.model')">
              <el-input
                v-model="productForm.formData.model"
                :placeholder="
                  $t('common.enter') +
                  $t('page.systemManageArr.productArr.model')
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.productArr.unit')">
              <el-select
                v-model="productForm.formData.unitId"
                :placeholder="
                  $t('common.select') +
                  $t('page.systemManageArr.productArr.unit')
                "
              >
                <el-option
                  v-for="item in productForm.resoure.calcUnitArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.systemManageArr.productArr.type')">
              <el-select
                v-model="productForm.formData.typeName"
                :placeholder="
                  $t('common.select') +
                  $t('page.systemManageArr.productArr.type')
                "
              >
                <el-option
                  v-for="productType in Object.keys(productTypeEnum)"
                  :key="productType"
                  :label="
                    $t(
                      `page.systemManageArr.productArr.productTypeArr.${productType}`
                    )
                  "
                  :value="productType"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.status')">
              <el-radio-group v-model="productForm.formData.status">
                <el-radio :label="true">{{
                  $t("table.btnArr.enable")
                }}</el-radio>
                <el-radio :label="false">{{
                  $t("table.btnArr.disEnable")
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-card>
        <!-- 产品管理属性 -->
        <el-card
          v-for="relAttr in Object.keys(ProductRelAttrUtils.relAttrMap)"
          :key="relAttr"
          class="el-card-bottom-top"
        >
          <template #header>
            <span>{{
              $t(`page.systemManageArr.productArr.relAttrArr.${relAttr}`)
            }}</span>
          </template>
          <!-- 产品关联属性表格 -->
          <ProductRelAttrTable :relAttr="relAttr" />
        </el-card>
      </el-form>
    </template>
  </DileDrawer>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, nextTick, toRef } from "vue";
import type { object_Inf } from "@/utils/typings/index.type";
import { useI18n } from "vue-i18n";
import { ElNotification } from "element-plus";
import { productTypeEnum } from "@/utils/typings/systemManage/index.type";
import ProductRelAttrTable from "../product-relAttrTable/index.vue";
import ProductRelAttrUtils from "../product-relAttrTable/utils";
import DileDrawer from "@/components/dile-drawer/index.vue";
import Dile_APi from "@/api";
import Dile_Methods from "@/utils/methods";

const emit = defineEmits(["refresh"]);

let { t } = useI18n();
/**
 * @Author: xzh
 * @Descripttion: 表单默认数据
 * @Param:
 */
let defaultData = () => {
  return {
    id: 0,
    status: true, //状态
    code: "", //产品编号
    name: "", //产品名称
    categoryId: null, //产品分类
    model: "", //产品型号
    unitId: "", //单位
    typeName: "", //产品类型
    extJson: {},
  };
};
/**
 * @Author: xzh
 * @Descripttion: 产品表单参数
 * @Param:
 */
let productForm = reactive<object_Inf>({
  visible: false,
  loading: false,
  //表单数据
  formData: defaultData(),
  resoure: {
    //计量单位
    calcUnitArr: [],
    //产品类别
    productClassifyArr: [],
  },
});

/**
 * @Author: xzh
 * @Descripttion: 表单实例
 * @Param:
 */
let formRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion:表单验证规则
 * @Param:
 * @param {*} computed
 */
let formRules = computed((): any => {
  return reactive({
    code: [
      {
        required: true,
        message: t("common.enter") + t("page.systemManageArr.productArr.code"),
        trigger: "change",
      },
    ],
  });
});

/**
 * @Author: xzh
 * @Descripttion:初始化加载
 * @Param:
 * @param {*} id 产品主键
 */
let init = async (id: number) => {
  let { visible, loading } = toRefs(productForm);
  visible.value = true;
  await nextTick();
  try {
    loading.value = true;
    //加载表单资源
    await initSearchResource();
    //加载表单数据
    await initFormData(id);
  } finally {
    loading.value = false;
  }
};
/**
 * @Author: xzh
 * @Descripttion: 加载表单资源
 * @Param:
 */
let initSearchResource = async () => {
  //加载计量单位资源
  await initCalcUnitArrResource();
  //加载产品类别资源
  await initProductClassifyArrResource();
};

/**
 * @Author: xzh
 * @Descripttion: 加载计量单位资源
 * @Param:
 */
let initCalcUnitArrResource = async () => {
  let calcUnitArr = toRef(productForm.resoure, "calcUnitArr");
  //加载所有设备状态
  calcUnitArr.value = Dile_Methods.filterDataArr(
    (await Dile_APi.getCalcUnitList())?.map((calcUnit: object_Inf) => ({
      value: calcUnit.id,
      label: calcUnit.name,
    }))
  );
};
/**
 * @Author: xzh
 * @Descripttion: 加载产品类别
 * @Param:
 */
let initProductClassifyArrResource = async () => {
  let productClassifyArr = toRef(productForm.resoure, "productClassifyArr");
  //加载所有设备状态
  productClassifyArr.value = Dile_Methods.filterDataArr(
    (await Dile_APi.getProductClassifyList())?.map(
      (productClassify: object_Inf) => ({
        value: productClassify.id,
        label: productClassify.name,
      })
    )
  );
};

/**
 * @Author: xzh
 * @Descripttion: 加载表单数据
 * @Param:
 */
let initFormData = async (id: number) => {
  let { model }: object_Inf = !!id
    ? await Dile_APi.getProductInfo(id)
    : { model: defaultData() };
  Object.assign(productForm.formData, model);
};

/**
 * @Author: xzh
 * @Descripttion: 保存事件
 * @Param:
 */
let hanldeSure = async () => {
  let { formData, loading, visible } = toRefs(productForm),
    valid = await formRef.value.validate();
  if (!valid || !!loading.value) {
    return false;
  }
  try {
    loading.value = true;
    await Dile_APi.saveProduct({ model: formData.value });
    //触发刷新回调
    emit("refresh");
    //提示成功
    ElNotification({
      message: t("common.message.OperationSuccess"),
      type: "success",
    });
    //关闭弹框
    visible.value = false;
  } finally {
    loading.value = false;
  }
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped></style>
